package com.nuc.thread.reentrantlock;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 测试ReentrantLock的锁超时
 * @createTime 2021年07月10日 11:20:00
 */
@Slf4j(topic = "test3")
public class Test3 {
    private static ReentrantLock lock = new ReentrantLock();
    @SneakyThrows
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            log.debug("尝试获取锁");
            boolean b = false;
            try {
                b = lock.tryLock(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!b){
                log.debug("没有获取到锁");
                return;
            }
            try{
                log.debug("获取到锁");
            }finally {
                lock.unlock();
            }
        }, "t1");

        log.debug("获取到锁");
        lock.lock();
        t1.start();
        Thread.sleep(1000);
        log.debug("释放锁");
        lock.unlock();

    }


}
